package com.gjy.shiro.simple;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-09-01 15:00:09
 */
public class PasswordUtil {

    public static String md5(String raw) {
        return DigestUtils.md5Hex(raw);
    }

    public static final String ALGORITHM = "SHA-256";
    public static final int ITERATIONS = 1024;

    /**
     * 生成带随机盐的密码（存入数据库）
     * 返回格式：salt:hash
     */
    public static String encrypt(String rawPassword) {
        // 随机 16 字节盐
        ByteSource salt = ByteSource.Util.bytes(new SecureRandomNumberGenerator().nextBytes(16).getBytes());
        String hash = new SimpleHash(ALGORITHM, rawPassword, salt, ITERATIONS).toHex();
        // 把盐和密文一起保存，方便校验
        return salt.toBase64() + ":" + hash;
    }

    /**
     * 校验密码
     * stored: salt:hash
     */
    public static boolean verify(String rawPassword, String stored) {
        String[] arr = stored.split(":");
        ByteSource salt = ByteSource.Util.bytes(org.apache.shiro.codec.Base64.decode(arr[0]));
        String expected = new SimpleHash(ALGORITHM, rawPassword, salt, ITERATIONS).toHex();
        return expected.equals(arr[1]);
    }

}
